﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio;
using IServiceProvider = System.IServiceProvider;
using System.IO;

namespace Timtopia.DGMLPosterView
{
    class VsShell
    {
        static IServiceProvider _provider;
        public static IServiceProvider Provider
        {
            get { return _provider; }
            set { _provider = value; }
        }

        public static IVsWindowPane GetActiveDocumentWindowPane()
        {
            IVsWindowFrame frame = GetActiveDocumentWindowFrame();
            return GetWindowPaneFromFrame(frame);
        }

        public static IVsWindowFrame GetActiveDocumentWindowFrame()
        {
            IVsMonitorSelection selection = (IVsMonitorSelection)_provider.GetService(typeof(SVsShellMonitorSelection));
            if (selection != null)
            {
                object pvar = null;
                if (ErrorHandler.Succeeded(selection.GetCurrentElementValue(
                        (uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out pvar)))
                {
                    IVsWindowFrame frame = pvar as IVsWindowFrame;
                    return frame;
                }
            }
            return null;
        }

        public static IVsWindowPane GetWindowPaneFromFrame(IVsWindowFrame frame)
        {
            if (frame != null)
            {
                object docView = null;
                if (ErrorHandler.Succeeded(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView,
                    out docView)))
                {
                    return docView as IVsWindowPane;
                }
            }
            return null;
        }

        public static string GetSolutionDirectory()
        {
            var solution = (IVsSolution)_provider.GetService(typeof(SVsSolution));
            string slnDirectory, slnFile, userFile;
            solution.GetSolutionInfo(out slnDirectory, out slnFile, out userFile);
            return slnDirectory;
        }
    }
}
